package com.automation.app;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.time.temporal.TemporalUnit;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class DianPingShopCrawler {

    public static AndroidDriver driver;
    public static WebDriverWait wait;

    public DianPingShopCrawler(AndroidDriver driver) {
        this.driver = driver;
        this.wait = new WebDriverWait(driver, Duration.ofMinutes(30));
    }

    public void crawlShops() throws InterruptedException {
        // 等待列表加载完成
        wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("//android.support.v7.widget.RecyclerView")
        ));

        int scrollAttempts = 0;
        final int MAX_SCROLL_ATTEMPTS = 10;

        while (scrollAttempts < MAX_SCROLL_ATTEMPTS) {
            // 获取当前屏幕可见的商户列表
            List<WebElement> shops = getVisibleShops();
            if (shops.isEmpty()) break;

            // 遍历当前页商户
            for (int i = 0; i < shops.size(); i++) {
                // 重新获取元素防止StaleReference
                List<WebElement> currentShops = getVisibleShops();
                if (i >= currentShops.size()) break;

                WebElement shop = currentShops.get(i);
                System.out.println("点击第 " + (i + 1) + " 个商户");
                shop.click();

                // 等待详情页加载
                waitForDetailPage();
                // 模拟查看详情（可根据需要扩展）
                Thread.sleep(2000);

                // 返回列表页
                goBackToList();
                // 等待列表重新加载
                wait.until(ExpectedConditions.presenceOfElementLocated(
                        By.xpath("//android.support.v7.widget.RecyclerView")
                ));
            }

            // 滚动加载新商户
            System.out.println("滚动加载新商户...");
            scrollDown();
            scrollAttempts++;
            Thread.sleep(3000); // 等待新内容加载
        }
    }

    private List<WebElement> getVisibleShops() {
        // 定位所有可见商户项（通过ViewGroup和FrameLayout组合定位）
        return driver.findElements(By.xpath(
                "//android.view.ViewGroup/android.widget.FrameLayout" +
                        "[@clickable='true' and @bounds[contains(.,']][900,')]]"
        ));
    }

    private void waitForDetailPage() {
        // 等待详情页特有元素（示例：店铺名称元素）
        wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("//android.widget.TextView[contains(@text, '店')]")
        ));
    }

    private void goBackToList() {
        // Android物理返回键
        driver.pressKey(new KeyEvent(AndroidKey.BACK));
    }

    private void scrollDown() {

        Dimension screenSize = driver.manage().window().getSize();
        int centerX = screenSize.width / 2;
        // 执行滚动（从底部滑动到顶部）
        new TouchAction(driver)
                .press(PointOption.point(centerX, (int)(screenSize.height * 0.8)))
                .waitAction(WaitOptions.waitOptions(Duration.ofMillis(800)))
                .moveTo(PointOption.point(centerX, (int)(screenSize.height * 0.3)))
                .release()
                .perform();
    }
}